<?php
/**
* productmodel.php
*
* Create on 2014-12-27
* Create by TT
*/
namespace haibao\cms\data;

use \haibao\cms\model\filter\Product as ProductFilter;

class ProductModel extends \haibao\cms\data\BaseMysql{

	private static $productInfo = null;
	private static $migrationMap = array();
	private static $categoryArr = array();
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ProductModel');
	}
	
	public function getProductPicById($id){
	    return parent::getOneById($id);
	}
	
	/**
	 * 得到单品下的所有实体
	 * @param \haibao\cms\model\filter\ProductModel $filter
	 */
	public function getModelsByProductId($filter){
		return parent::getAll($filter);
	}

	/**
	 * 得到某一单品实体
	 * @param \haibao\cms\model\filter\ProductModel $filter
	 */
	public function getOneModel($filter){
		return parent::getOne($filter);	
	}
	
	/**
	 * 添加单品模型
	 * @param \haibao\cms\model\data\ProductModel $model	单品模型实体
	 */
	public function addProduct($model,$userName){
		self::beginTranscation();
		try{
			parent::add($model);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		$imageData = new \haibao\cms\data\ImageLibrary();
		$imageData->updateImageStatus($model->PicId,\haibao\cms\model\data\ImageLibrary::STATUS_ENABLE, $userName);
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			//添加老记录
			$this->addOldData($model,$userName);
		}
	}
	/**
	 * 批量修改单品模型
	 * @param array $ids	单品模型IDS
	 * @param array $arrSet 需要修改的字段
	 * @param array(\haibao\cms\model\data\ProductModelProperty) $modelPropertyModes 需要修改的字段
	 */
	public function batchUpdateProduct($ids,$arrSet,$modelPropertyModes,$userName){
		
		self::beginTranscation();
		try{
			$productFilter = new ProductFilter();
			$productFilter->where(ProductFilter::CONDITION_FIELD_NAME_ID, \haibao\frame\data\query\Condition::CONDITION_IN, $ids);
			self::update($arrSet, $productFilter);
			
			$this->updateBrandUpdateTime($ids[0]);
			
			if($modelPropertyModes){
				//先删除单品模型属性值
				$str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
				$sql = 'delete from ProductModelProperty where ProductModelId   in (' . $str . ')';
				$this->query($sql,$ids);
				//再添加
				$arrValues = array();
				$arrSql = array();
				foreach($modelPropertyModes as $models){
					foreach($models as $model){
						array_push($arrSql,'(%s,%s,%s)');
						array_push($arrValues,$model->PropertyId);
						array_push($arrValues,$model->ProductModelId);
						array_push($arrValues,$model->PropertyValue);
					}
				}
				$sql = "insert into ProductModelProperty (PropertyId, ProductModelId,PropertyValue) values";
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
			}
			
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			//修改老记录
			foreach($ids as $id){
				$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
				$productModel = parent::getOneById($id);
				$tableName = $productModel->getTableName();
				$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey =%s';
				$result = $this->query($sql,array($id));
				$oldProduct = 0;
				while ($result->fetch_assoc())
				{
					$oldProduct = $result->getData('OldPrimaryKey');
				}
				
				$newPropertyTooldPropertyId = array();
				
				if($modelPropertyModes){
					$propertyId = array();
					foreach($modelPropertyModes[$id] as $model){
						$propertyId[] = $model->PropertyId;
					}
					
					$productPropertyModel = new \haibao\cms\model\data\ProductCategoryProperty();
					$tableName = $productPropertyModel->getTableName();
					$str = preg_replace('/(\d+)/', '%s', implode(',', $propertyId));
					$sql = 'select OldPrimaryKey,PrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in('.$str.')';
					$result = $this->query($sql,$propertyId);
					while ($result->fetch_assoc())
					{
						$newPropertyTooldPropertyId[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
					}
				}
				
				if($oldProduct){
					$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
					//修改brand_product表
					$picUrl = $this->getPicUrl($productModel->PicId);
					$picUrl = ltrim($picUrl,'/');
					$sql = 'update brand_product set product_name="'.$productModel->ProductName.'",pic=%s,picdesc=%s where id=%s';
					$this->query($sql,array($picUrl,$productModel->PicDesc,$oldProduct));
					//修改brand_product_info表
					if($modelPropertyModes && $newPropertyTooldPropertyId){
						//先删除
						$sql = 'delete from brand_product_info where product_id=%s';
						$this->query($sql,array($oldProduct));
						//再添加
						$arrValues = array();
						$arrSql = array();
						$dateTime = new \DateTime();
						foreach($modelPropertyModes[$id] as $model){
							array_push($arrSql,'(%s,%s,%s,%s,%s)');
							array_push($arrValues,$oldProduct);
							if(!empty($newPropertyTooldPropertyId[$model->PropertyId])){
								array_push($arrValues,$newPropertyTooldPropertyId[$model->PropertyId]);
							}else{
								array_push($arrValues,'');
							}
							array_push($arrValues,$model->PropertyValue);
							array_push($arrValues,$userName);
							array_push($arrValues,$dateTime->format('Y-m-d H:i:s'));
						}
						if($arrValues){
							$sql = "insert into brand_product_info (product_id, param_small_id,content,username,date) values";
							$sql .= implode(',', $arrSql);
							$this->query($sql,$arrValues);
						}
					}
				}
			}
		}
	}
	/**
	 * 修改单品模型
	 * @param int $id	单品模型ID
	 * @param array $arrSet 需要修改的字段
	 * @param array(\haibao\cms\model\data\ProductModelProperty) $modelPropertyModes 需要修改的字段
	 */
	public function updateProduct($id,$arrSet,$modelPropertyModes,$userName){
		self::beginTranscation();
		try{
			parent::updateById($id, $arrSet);
			
			$this->updateBrandUpdateTime($id);
			
			if($modelPropertyModes){
				//先删除单品模型属性值
				$sql = 'delete from ProductModelProperty where ProductModelId=%s';
				$this->query($sql,array($id));
				//再添加
				$arrValues = array();
				$arrSql = array();
				foreach($modelPropertyModes as $model){
					array_push($arrSql,'(%s,%s,%s)');
					array_push($arrValues,$model->PropertyId);
					array_push($arrValues,$model->ProductModelId);
					array_push($arrValues,$model->PropertyValue);
				}
				$sql = "insert into ProductModelProperty (PropertyId, ProductModelId,PropertyValue) values";
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
			}
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			//修改老记录
			$productModel = parent::getOneById($id);
			$tableName = $productModel->getTableName();
			$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey =%s';
			$result = $this->query($sql,array($id));
			$oldProduct = 0;
			while ($result->fetch_assoc())
			{
				$oldProduct = $result->getData('OldPrimaryKey');
			}
			
			try{
				if(empty($oldProduct)){
					$this->addOldData($productModel,$userName);
				} else {
					$newPropertyTooldPropertyId = array();
					if($modelPropertyModes){
						$propertyId = array();
						foreach($modelPropertyModes as $model){
							$propertyId[] = $model->PropertyId;
						}
						$productPropertyModel = new \haibao\cms\model\data\ProductCategoryProperty();
						$tableName = $productPropertyModel->getTableName();
						$str = preg_replace('/(\d+)/', '%s', implode(',', $propertyId));
						$sql = 'select OldPrimaryKey,PrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in('.$str.')';
						$result = $this->query($sql,$propertyId);
						while ($result->fetch_assoc())
						{
							$newPropertyTooldPropertyId[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
						}
					}
					$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
					//修改brand_product表
					$picUrl = $this->getPicUrl($productModel->PicId);
					$picUrl = ltrim($picUrl,'/');
					$sql = 'update brand_product set product_name="'.$productModel->ProductName.'",pic=%s,picdesc=%s where id=%s';
					$this->query($sql,array($picUrl,$productModel->PicDesc,$oldProduct));
					//修改brand_product_info表
					if($modelPropertyModes && $newPropertyTooldPropertyId){
						//先删除
						$sql = 'delete from brand_product_info where product_id=%s';
						$this->query($sql,array($oldProduct));
						//再添加
						$arrValues = array();
						$arrSql = array();
						$dateTime = new \DateTime();
						foreach($modelPropertyModes as $model){
							array_push($arrSql,'(%s,%s,%s,%s,%s)');
							array_push($arrValues,$oldProduct);
							if(!empty($newPropertyTooldPropertyId[$model->PropertyId])){
								array_push($arrValues,$newPropertyTooldPropertyId[$model->PropertyId]);
							}else{
								array_push($arrValues,'');
							}
							array_push($arrValues,$model->PropertyValue);
							array_push($arrValues,$userName);
							array_push($arrValues,$dateTime->format('Y-m-d H:i:s'));
						}
						if($arrValues){
							$sql = "insert into brand_product_info (product_id, param_small_id,content,username,date) values";
							$sql .= implode(',', $arrSql);
							$this->query($sql,$arrValues);
						}
					}
				}
			}catch (\Exception $e){
				throw $e;
			}
		}
	}
	
	public function updateStatusById($id,$status = \haibao\cms\model\data\product::STATUS_ENABLE){
		$sql = 'update ProductModel set Status=%s where Id=%s';
		$this->query($sql,array($status,$id));
		
		$this->updateBrandUpdateTime($id);
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$this->updateOldProduct(array($id),$status);
		}
	}
	
	
	public function updateStatusByProductId($productId,$status = \haibao\cms\model\data\product::STATUS_ENABLE){
		$sql = 'update ProductModel set Status=%s where ProductId=%s';
		$this->query($sql,array($status,$productId));
		
		//TT addtime 2015.11.26
		//修改品牌库某品牌记录的修改日期
		$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where Id in (SELECT BrandId from ProductBrandGroup where ProductId=%s)";
		$this->query($sql,array($productId));
		
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$productModelIds = array();
			$sql = 'select Id from ProductModel where ProductId=%s';
			$result = $this->query($sql,array($productId));
			while ($result->fetch_assoc())
			{
				$productModelIds[] = $result->getData('Id');
			}
			if($productModelIds){
				$this->updateOldProduct($productModelIds,$status);
			}
		}
	}
	
	//TT addtime 2015.11.26
	//修改品牌库某品牌记录的修改日期
	private function updateBrandUpdateTime($productModelId){
		$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where Id in (SELECT BrandId from ProductBrandGroup where ProductId in (SELECT ProductId from ProductModel where id=%s))";
		$this->query ($sql, array($productModelId));
	}
	
	/**
	 * 更新单品发布ID
	 * @param unknown_type $productModelId
	 */
	private function updatePublistId($productModelId,$publishId = 0){
		if(empty($publishId)){
			$publishId = $productModelId;
		}
		$sql = "update ProductModel set PublishId=".$publishId." where Id =".$productModelId;
		$this->query ( $sql );
	}
	
	private function updateOldProduct($productModelIds,$status){
		$productModel = new \haibao\cms\model\data\ProductModel();
		$tableName = $productModel->getTableName();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $productModelIds));
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in('.$str.')';
		$result = $this->query($sql,$productModelIds);
		$oldProduct = array();
		while ($result->fetch_assoc())
		{
			$oldProduct[] = $result->getData('OldPrimaryKey');
		}
			
		if($oldProduct){
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$str = preg_replace('/(\d+)/', '%s', implode(',', $oldProduct));
			$sql = 'update brand_product set status=%s where id in ('.$str.')';
			array_unshift($oldProduct, $status);
			$this->query($sql,$oldProduct);
		}
	}
	
	/**
	 * 删除产品模型
	 * @param array(int) $ids
	 */
	public function delProduct($ids,$userName){
		self::beginTranscation();
		try{
			//先根据ID得到图片ID
			$str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
			$picId = array();
			$sql = 'select PicId from ProductModel where Id in ('.$str.')';
			$result = $this->query($sql,$ids);
			while ($result->fetch_assoc())
			{   
				$picId[] = $result->getData('PicId');
			}
			//删除
			$sql = 'delete from ProductModel where Id in ('.$str.')';
			$this->query($sql,$ids);
			
			//删除属性表
			$sql = 'delete from ProductModelProperty where ProductModelId in ('.$str.')';
			$this->query($sql,$ids);
			
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
			
		//删除图片
		$imageData = new \haibao\cms\data\ImageLibrary();
		$imageData->updateImageStatus($picId,\haibao\cms\model\data\ImageLibrary::STATUS_DISABLE,$userName);
		
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
			//删除老记录
			$productModel = new \haibao\cms\model\data\ProductModel();
			$tableName = $productModel->getTableName();
			$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in ('.$str.')';
			$result = $this->query($sql,$ids);
			$oldProduct = array();
			while ($result->fetch_assoc())
			{
				$oldProduct[] = $result->getData('OldPrimaryKey');
			}
			
			$sql = 'delete from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in ('.$str.')';
			$this->query($sql,$ids);
			
			if($oldProduct){
				$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
				$str = preg_replace('/(\d+)/', '%s', implode(',', $oldProduct));
				$sql = 'delete from brand_product where id in ('.$str.')';
				$this->query($sql,$oldProduct);
				
				$sql = 'delete from brand_product_info where product_id in ('.$str.')';
				$this->query($sql,$oldProduct);
			}
		}
	}
	
	private function addOldData($model,$userName){
		//添加brand_product
		self::$productInfo = null;
		self::$migrationMap = array();
		self::$categoryArr = array();
		$this->getProductInfo($model->ProductId);
		//取group_id
		$this->getGroupId($model->ProductId);
		if(isset(self::$migrationMap['OldPrimaryKey'])){
			//取大小类别ID
			$this->getCategoryArr(self::$productInfo->CategoryId);
			
			//得图片路径
			$picUrl = $this->getPicUrl($model->PicId);
			$picUrl = ltrim($picUrl,'/');
			$productName = $model->ProductName;
			if(empty($productName)){
				$productName = '';
			}
			$productDesc = $model->PicDesc;
			if(empty($productDesc)){
				$productDesc = '';
			}
			$material = '';
			if(self::$productInfo->Material){
				$material = self::$productInfo->Material;
			}
			$fashionElement = '';
			if(self::$productInfo->FashionElement){
				$material = self::$productInfo->FashionElement;
			}
			$color = '';
			if(self::$productInfo->Color){
				$material = self::$productInfo->Color;
			}
			$sql = 'insert into brand_product (group_id,product_name,brand_id_up,category_id1,category_id2,score,season,season_year,product_line,material,fashelement,color,status,pic,picdesc,username,date) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)';
			$arrValues = array(self::$migrationMap['OldPrimaryKey'],$productName,self::$productInfo->SuperBrandId,self::$categoryArr['bigId'],
					self::$categoryArr['smallId'],0,self::$productInfo->Season,self::$productInfo->SeasonYear,self::$productInfo->ProductSeries,
					$material,$fashionElement,$color,self::$productInfo->Status,
					$picUrl,$productDesc,$userName,$model->CreateTime->format('Y-m-d H:i:s'));
			
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$this->query($sql,$arrValues);
			$productOldId = $this->getDb()->insert_id;
			
			//添加新老数据对应表DataMigrationMap
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
			$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) values(%s,%s,%s)";
			$arrValues = array($model->getTableName(),$model->Id,$productOldId);
			$this->query($sql,$arrValues);
			$this->updatePublistId($model->Id,$productOldId);
		}
	}
	
	private function getProductInfo($productId){
		$productData = new \haibao\cms\data\Product();
		if(empty(self::$productInfo)){
			self::$productInfo = $productData->getOneById($productId);
		}
		else if(self::$productInfo->Id != $productId){
			self::$productInfo = $productData->getOneById($productId);
		}
	}
	
	private function getCategoryArr($smallCategoryId){
		$productCategoryData = new \haibao\cms\data\ProductCategoryDefine();
		$productCategoryModel = $productCategoryData->getCategoryById($smallCategoryId);
		if($productCategoryModel){
			$bigId = $productCategoryModel->ParentId;
			$primaryKey = array($smallCategoryId,$bigId);
			$str = preg_replace('/(\d+)/', '%s', implode(',', $primaryKey));
			$tableName = $productCategoryModel->getTableName();
			if(empty(self::$categoryArr)){
				self::$categoryArr['smallId'] = 0;
				self::$categoryArr['bigId'] = 0;
				$sql = 'select OldPrimaryKey,PrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in ('.$str.')';
				$result = $this->query($sql,$primaryKey);
				while ($result->fetch_assoc())
				{
					if($result->getData('PrimaryKey') == $smallCategoryId){
						self::$categoryArr['smallId'] = $result->getData('OldPrimaryKey');
					} else {
						self::$categoryArr['bigId'] = $result->getData('OldPrimaryKey');
					}
				}
			}
			else if(self::$categoryArr['smallId'] != $smallCategoryId){
				self::$categoryArr['smallId'] = 0;
				self::$categoryArr['bigId'] = 0;
				$sql = 'select OldPrimaryKey,PrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey in ('.$str.')';
				$result = $this->query($sql,$primaryKey);
				while ($result->fetch_assoc())
				{
					if($result->getData('PrimaryKey') == $smallCategoryId){
						self::$categoryArr['smallId'] = $result->getData('OldPrimaryKey');
					} else {
						self::$categoryArr['bigId'] = $result->getData('OldPrimaryKey');
					}
				}
			}
		}
	}
	
	private function getGroupId($productId){
		$productModel = new \haibao\cms\model\data\Product();
		$tableName = $productModel->getTableName();
		if(empty(self::$migrationMap)){
			$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey=%s';
			$result = $this->query($sql,array($productId));
			while ($result->fetch_assoc())
			{
				self::$migrationMap['OldPrimaryKey'] = $result->getData('OldPrimaryKey');
			}
			self::$migrationMap['TableName'] = $tableName;
			self::$migrationMap['PrimaryKey'] = $productId;
		} else if(self::$migrationMap['PrimaryKey'] != $productId || self::$migrationMap['TableName'] != $tableName) {
			$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="'.$tableName.'" and PrimaryKey=%s';
			$result = $this->query($sql,array($productId));
			while ($result->fetch_assoc())
			{
				self::$migrationMap['OldPrimaryKey'] = $result->getData('OldPrimaryKey');
			}
			self::$migrationMap['TableName'] = $tableName;
			self::$migrationMap['PrimaryKey'] = $productId;
		}
	}
	
	private function getPicUrl($picId){
		$imageData = new \haibao\cms\data\ImageLibrary();
		return $imageData->getImageUrl($picId);
	}
	public function getAllDataMigrationMap($productIds,$isNew = true){
		$dataMap = array();
		$productIds = implode(',',$productIds);
		if($isNew){
			$sql = 'select PrimaryKey,OldPrimaryKey from `DataMigrationMap` where `TableName`=%s and `PrimaryKey` in ('.$productIds.')';
		}else{
				
		}
		$result = $this->query($sql,array('ProductModel'));
	
		while($result->fetch_assoc()){
			$id = $result->getData('PrimaryKey');
			$dataMap[$id] = $result->getData('OldPrimaryKey');
		}
		return $dataMap;
	}
}